<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Radio,
  RadioGroup,
  Row,
  Select,
  SelectOption,
  Switch,
} from 'ant-design-vue';

// Props
const props = defineProps<{
  field: any;
}>();

// Emits
const emit = defineEmits<{
  cancel: [];
  update: [field: any];
}>();

// 响应式数据
const saving = ref(false);
const fieldData = reactive({
  id: '',
  name: '',
  label: '',
  type: 'STRING',
  required: false,
  defaultValue: '',
  options: [],
  validation: {
    minLength: undefined,
    maxLength: undefined,
    min: undefined,
    max: undefined,
    pattern: '',
    customRule: '',
  },
  uiConfig: {
    placeholder: '',
    helpText: '',
    width: '',
    showLabel: true,
    layout: 'horizontal',
  },
});

// 监听props变化
watch(
  () => props.field,
  (newField) => {
    if (newField) {
      Object.assign(fieldData, {
        id: newField.id || '',
        name: newField.name || '',
        label: newField.label || '',
        type: newField.type || 'STRING',
        required: newField.required || false,
        defaultValue: newField.defaultValue || '',
        options: newField.options || [],
        validation: {
          minLength: newField.validation?.minLength,
          maxLength: newField.validation?.maxLength,
          min: newField.validation?.min,
          max: newField.validation?.max,
          pattern: newField.validation?.pattern || '',
          customRule: newField.validation?.customRule || '',
        },
        uiConfig: {
          placeholder: newField.uiConfig?.placeholder || '',
          helpText: newField.uiConfig?.helpText || '',
          width: newField.uiConfig?.width || '',
          showLabel: newField.uiConfig?.showLabel !== false,
          layout: newField.uiConfig?.layout || 'horizontal',
        },
      });
    }
  },
  { immediate: true, deep: true },
);

// 方法
const updateFieldName = () => {
  // 如果标签为空，自动使用字段名作为标签
  if (!fieldData.label && fieldData.name) {
    fieldData.label = fieldData.name;
  }
};

const onTypeChange = (type: string) => {
  // 根据类型重置相关配置
  if (type === 'ENUM' && fieldData.options.length === 0) {
    fieldData.options = [
      { label: '选项1', value: 'option1' },
      { label: '选项2', value: 'option2' },
    ];
  } else if (type !== 'ENUM') {
    fieldData.options = [];
  }

  // 重置验证规则
  if (type !== 'STRING') {
    fieldData.validation.minLength = undefined;
    fieldData.validation.maxLength = undefined;
  }
  if (type !== 'NUMBER') {
    fieldData.validation.min = undefined;
    fieldData.validation.max = undefined;
  }
};

const addOption = () => {
  fieldData.options.push({
    label: `选项${fieldData.options.length + 1}`,
    value: `option${fieldData.options.length + 1}`,
  });
};

const removeOption = (index: number) => {
  fieldData.options.splice(index, 1);
};

const saveField = async () => {
  // 验证必填字段
  if (!fieldData.name) {
    message.error('请输入字段名称');
    return;
  }

  if (!fieldData.label) {
    message.error('请输入显示标签');
    return;
  }

  if (fieldData.type === 'ENUM' && fieldData.options.length === 0) {
    message.error('请至少添加一个枚举选项');
    return;
  }

  saving.value = true;
  try {
    // 模拟保存
    await new Promise((resolve) => setTimeout(resolve, 500));

    const updatedField = { ...fieldData };
    emit('update', updatedField);
    message.success('字段配置保存成功');
  } catch {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};
</script>

<template>
  <div class="field-editor">
    <div class="editor-header">
      <h3>字段配置</h3>
      <div class="header-actions">
        <Button type="primary" @click="saveField" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存
        </Button>
        <Button @click="$emit('cancel')">
          <IconifyIcon icon="ant-design:close-outlined" />
          取消
        </Button>
      </div>
    </div>

    <div class="editor-content">
      <Form
        :model="fieldData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <!-- 基本信息 -->
        <div class="section">
          <h4>基本信息</h4>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="字段名称" name="name">
                <Input
                  v-model:value="fieldData.name"
                  placeholder="请输入字段名称"
                  @change="updateFieldName"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="显示标签" name="label">
                <Input
                  v-model:value="fieldData.label"
                  placeholder="请输入显示标签"
                />
              </FormItem>
            </Col>
          </Row>

          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="字段类型" name="type">
                <Select
                  v-model:value="fieldData.type"
                  placeholder="请选择字段类型"
                  @change="onTypeChange"
                >
                  <SelectOption value="STRING">文本</SelectOption>
                  <SelectOption value="NUMBER">数字</SelectOption>
                  <SelectOption value="BOOLEAN">布尔值</SelectOption>
                  <SelectOption value="DATE">日期</SelectOption>
                  <SelectOption value="ENUM">枚举</SelectOption>
                  <SelectOption value="TEXTAREA">多行文本</SelectOption>
                  <SelectOption value="FILE">文件</SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="是否必填" name="required">
                <Switch v-model:checked="fieldData.required" />
              </FormItem>
            </Col>
          </Row>

          <FormItem label="默认值" name="defaultValue">
            <Input
              v-model:value="fieldData.defaultValue"
              placeholder="请输入默认值"
            />
          </FormItem>
        </div>

        <!-- 枚举选项 -->
        <div class="section" v-if="fieldData.type === 'ENUM'">
          <h4>枚举选项</h4>
          <div class="enum-options">
            <div
              v-for="(option, index) in fieldData.options"
              :key="index"
              class="option-item"
            >
              <Input
                v-model:value="option.label"
                placeholder="选项标签"
                style="width: 200px"
              />
              <Input
                v-model:value="option.value"
                placeholder="选项值"
                style="width: 200px"
              />
              <Button type="text" danger @click="removeOption(index)">
                <IconifyIcon icon="ant-design:delete-outlined" />
              </Button>
            </div>
            <Button type="dashed" @click="addOption">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加选项
            </Button>
          </div>
        </div>

        <!-- 验证规则 -->
        <div class="section">
          <h4>验证规则</h4>
          <Row :gutter="16">
            <Col :span="12" v-if="fieldData.type === 'STRING'">
              <FormItem label="最小长度" name="validation.minLength">
                <InputNumber
                  v-model:value="fieldData.validation.minLength"
                  :min="0"
                  placeholder="最小长度"
                />
              </FormItem>
            </Col>
            <Col :span="12" v-if="fieldData.type === 'STRING'">
              <FormItem label="最大长度" name="validation.maxLength">
                <InputNumber
                  v-model:value="fieldData.validation.maxLength"
                  :min="0"
                  placeholder="最大长度"
                />
              </FormItem>
            </Col>
          </Row>

          <Row :gutter="16">
            <Col :span="12" v-if="fieldData.type === 'NUMBER'">
              <FormItem label="最小值" name="validation.min">
                <InputNumber
                  v-model:value="fieldData.validation.min"
                  placeholder="最小值"
                />
              </FormItem>
            </Col>
            <Col :span="12" v-if="fieldData.type === 'NUMBER'">
              <FormItem label="最大值" name="validation.max">
                <InputNumber
                  v-model:value="fieldData.validation.max"
                  placeholder="最大值"
                />
              </FormItem>
            </Col>
          </Row>

          <FormItem label="正则表达式" name="validation.pattern">
            <Input
              v-model:value="fieldData.validation.pattern"
              placeholder="请输入正则表达式"
            />
          </FormItem>

          <FormItem label="自定义验证" name="validation.customRule">
            <Input.TextArea
              v-model:value="fieldData.validation.customRule"
              placeholder="请输入自定义验证规则"
              :rows="3"
            />
          </FormItem>
        </div>

        <!-- UI配置 -->
        <div class="section">
          <h4>UI配置</h4>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="占位符" name="uiConfig.placeholder">
                <Input
                  v-model:value="fieldData.uiConfig.placeholder"
                  placeholder="请输入占位符"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="帮助文本" name="uiConfig.helpText">
                <Input
                  v-model:value="fieldData.uiConfig.helpText"
                  placeholder="请输入帮助文本"
                />
              </FormItem>
            </Col>
          </Row>

          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="字段宽度" name="uiConfig.width">
                <Input
                  v-model:value="fieldData.uiConfig.width"
                  placeholder="如: 200px, 50%"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="显示标签" name="uiConfig.showLabel">
                <Switch v-model:checked="fieldData.uiConfig.showLabel" />
              </FormItem>
            </Col>
          </Row>

          <FormItem label="布局方式" name="uiConfig.layout">
            <RadioGroup v-model:value="fieldData.uiConfig.layout">
              <Radio value="horizontal">水平布局</Radio>
              <Radio value="vertical">垂直布局</Radio>
            </RadioGroup>
          </FormItem>
        </div>
      </Form>
    </div>
  </div>
</template>

<style lang="less" scoped>
.field-editor {
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .editor-content {
    .section {
      margin-bottom: 32px;

      h4 {
        margin: 0 0 16px 0;
        font-size: 14px;
        font-weight: 600;
        color: #333;
        padding-left: 8px;
        border-left: 3px solid #1890ff;
      }
    }

    .enum-options {
      .option-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
